package com.fysports.web.module.breadcrumb;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.fysports.web.kit.cache.DictCacheKit;
import com.fysports.web.kit.commons.WebContextKit;
import com.fysports.web.model.system.SystemMenu;
import com.fysports.web.module.core.BaseWebManagerModule;
import com.fysports.web.module.core.ModuleException;
import com.fysports.web.module.view.BreadcrumbView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 后台管理主内容区域的面包屑生成<br/>
 * Created by konbluesky<br/>
 * Date : 14-8-13 下午9:37<br/>
 * Project : JdmData_WebServer<br/>
 */
public class BreadcrumbModule extends BaseWebManagerModule {

    public BreadcrumbModule(HttpServletRequest req) {
        super(req);
    }


    private static String REQ_VIEW_BREADCRUMB = "breadcrumbView";


    @Override
    public void execute() throws ModuleException {
        /**
         * url=/luxcon.server/goto?go=system/druid/_druid.html&m=menu,bread
         */
        String url = WebContextKit.getRequestURIWithParam(getRequest());
        String appname = (String) getRequest().getAttribute("CONTEXT_PATH");
        SystemMenu sm = null;
        url = url.replace(appname, "");
        /**
         * 1.原url先查找一遍,有则略过
         * 2.url截断 逐段匹配(贪心匹配,匹配最符合条件的一个)
         * 比如:
         * http://localhost:8080/shop/user/rank/index/adafsdf  - url -> /user/rank
         */
        String sql="select * from "+SystemMenu.dao.getTable().getName()+" where url=?";
        sm=SystemMenu.dao.findFirstByCache(DictCacheKit.TMPCACHE,url,sql, url);
        if(sm==null) {
            Iterable<String> urls = Splitter.on("/").omitEmptyStrings().split(url);
            String tmpurl = "";
            //保存最终结果,当取sm取不到值时,pre回赋
            SystemMenu pre=null;
            for (String st : urls) {
                tmpurl += "/" + st;
                sm = SystemMenu.dao.findFirstByCache(DictCacheKit.TMPCACHE,tmpurl,sql, tmpurl);
                if (sm != null) {
                    pre = sm;
                    continue;
                }else {
                    break;
                }
            }
            sm=pre;
        }
        if (sm != null) {
            List list = sm.getParents();
            setAttr(REQ_VIEW_BREADCRUMB, new BreadcrumbView(list));
        } else {
            setAttr(REQ_VIEW_BREADCRUMB, getBreadcrumbView());
        }

    }


    /**
     * 如果无法通过url来取得菜单列表，则用此方法
     *
     * @return
     */
    private BreadcrumbView getBreadcrumbView() {
        BreadcrumbView bv = new BreadcrumbView();
        List<SystemMenu> list = Lists.newArrayList();
        SystemMenu sm = SystemMenu.dao.searchFirst(SystemMenu.COL_PARENTCODE, 0);
        list.add(sm);
        bv.setNodelist(list);
        return bv;
    }
}
